<template>
  <page-detail>
    <div class="form-container">
      <!-- 表单内容 -->
      <van-form ref="form" @submit="onSubmit">
        <!-- 积分内容 -->
        <van-field
          v-model="selectedRuleName"
          label="积分内容"
          placeholder="请选择积分内容"
          readonly
          clickable
          right-icon="arrow-down"
          @click="showRulePicker = true"
          :rules="[{ required: true, message: '请选择积分内容' }]"
        />

        <!-- 积分数量 -->
        <van-field
          v-model="formData.pointsNum"
          label="积分数量"
          readonly
          placeholder="请先选择积分内容"
        />

        <!-- 申请人姓名 -->
        <van-field
          v-model="formData.personName"
          label="申请人姓名"
          placeholder="请输入申请人姓名"
          :rules="[{ required: true, message: '请输入申请人姓名' }]"
        />

        <!-- 描述 -->
        <van-field
          v-model="formData.description"
          label="描述"
          type="textarea"
          placeholder="请详细描述积分申请的具体情况"
          autosize
          :rules="[{ required: true, message: '请输入描述' }]"
        />
        
        <!-- 证明材料上传 -->
        <div class="upload-section">
          <div class="upload-title">证明材料</div>
          <div class="upload-desc">请上传相关证明材料图片，最多3张</div>
          <ne-file-upload :max-file="3" v-model="formData.proofMaterialFiles" />
        </div>
      </van-form>
      
      <!-- 提交按钮 -->
      <div class="submit-section">
        <van-button 
          type="primary" 
          size="large" 
          round 
          @click="handleSubmit"
          :loading="submitting"
        >
          提交申请
        </van-button>
      </div>
    </div>

    <!-- 积分规则选择器 -->
    <van-popup v-model="showRulePicker" round position="bottom" :style="{ height: '60%' }">
      <div class="picker-container">
        <div class="picker-header">
          <span class="picker-title">选择积分内容</span>
          <van-icon name="cross" @click="showRulePicker = false" />
        </div>
        <div class="picker-content">
          <div
            v-for="rule in pointsRules"
            :key="rule.indexCode"
            class="rule-item"
            @click="selectRule(rule)"
          >
            <div class="rule-name">{{ rule.pointsName }}</div>
            <div class="rule-points">+{{ rule.pointsNum }}分</div>
          </div>
        </div>
      </div>
    </van-popup>
  </page-detail>
</template>

<script>
import request from '@/utils/http'
import { mapGetters } from 'vuex'
import { Toast } from 'vant'
import NeFileUpload from '../../components/NeFileUpload.vue'

export default {
  name: 'PointsApplicationAdd',
  components: { NeFileUpload },
  data() {
    return {
      submitting: false,
      showRulePicker: false,
      pointsRules: [],
      selectedRule: null,
      selectedRuleName: '',
      formData: {
        rulesId: '',
        pointsName: '',
        pointsNum: '',
        personName: '',
        description: '',
        proofMaterialFiles: []
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  onLoad() {
    this.getPointsRules()
  },
  methods: {
    async getPointsRules() {
      try {
        this.$showLoading('加载中...')
        const res = await request({
          url: '/tbPointsRules/list',
          method: 'post',
          data:{}
        })
        this.$hideLoading()

        if (res.code === '0') {
          this.pointsRules = res.data || []
        }
      } catch (error) {
        this.$hideLoading()
        console.error('获取积分规则失败:', error)
        Toast('获取积分规则失败')
      }
    },

    selectRule(rule) {
      this.selectedRule = rule
      this.selectedRuleName = rule.pointsName
      this.formData.rulesId = rule.indexCode
      this.formData.pointsName = rule.pointsName
      this.formData.pointsNum = rule.pointsNum
      this.showRulePicker = false
    },

    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    async handleSubmit() {
      try {
        // 表单验证
        await this.$refs.form.validate()
        
        // 检查是否上传了证明材料
        if (!this.formData.proofMaterialFiles.length) {
          Toast('请上传证明材料')
          return
        }
        
        this.submitting = true
        
        // 处理证明材料图片地址
        const proofMaterials = this.formData.proofMaterialFiles
          .map(file => file.url)
          .join(',')
        
        // 构建提交数据
        const currentTime = this.formatDateTime(new Date())
        const submitData = {
          userId: this.userInfo.userId,
          phone: this.userInfo.userId,
          personName: this.formData.personName,
          rulesId: this.formData.rulesId,
          pointsName: this.formData.pointsName,
          pointsNum: parseInt(this.formData.pointsNum),
          description: this.formData.description,
          proofMaterials: proofMaterials,
          createdTime: currentTime,
          updatedTime: currentTime
        }
        
        const res = await request({
          url: '/tbPointsApplication/save',
          method: 'post',
          data: submitData
        })
        
        this.submitting = false
        
        if (res.code === '0') {
          Toast.success('申请提交成功')
          // 通知列表页刷新数据
          uni.$emit('refreshPointsApplicationList')
          setTimeout(() => {
            this.$navigateBack()
          }, 1500)
        } else {
          Toast(res.msg || '提交失败')
        }
      } catch (error) {
        this.submitting = false
        console.error('提交积分申请失败:', error)
        if (typeof error === 'string') {
          Toast(error)
        } else {
          Toast('提交失败，请重试')
        }
      }
    }
  }
}
</script>

<style scoped>
.form-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.upload-section {
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 20rpx 0;
}

.upload-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.upload-desc {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 16rpx;
}

.submit-section {
  padding: 40rpx 20rpx;
  background: white;
  margin-top: 20rpx;
  border-radius: 16rpx;
}

.picker-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 40rpx;
  border-bottom: 1px solid #eee;
}

.picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.picker-content {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx;
}

.rule-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.rule-item:active {
  background-color: #f5f5f5;
}

.rule-name {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  margin-right: 20rpx;
}

.rule-points {
  font-size: 28rpx;
  font-weight: bold;
  color: #52c41a;
}
</style>
